<template>
  <div class="resume-builder">
    <div class="builder-header">
      <div class="header-left">
        <el-button type="text" @click="goBack">
          <el-icon><ArrowLeft /></el-icon>
          返回
        </el-button>
        <div class="resume-title">{{ resumeData?.title || '简历制作' }}</div>
      </div>
      <div class="header-right">
        <el-button @click="refreshStepsStatus" :loading="refreshing" size="small">
          <el-icon><Refresh /></el-icon>
          刷新状态
        </el-button>
        <el-button @click="handleSave" :loading="saving">
          <el-icon><Document /></el-icon>
          保存
        </el-button>
        <el-button
          v-if="allStepsCompleted"
          type="primary"
          @click="handleGenerate"
          :loading="generating"
        >
          <el-icon><Download /></el-icon>
          生成简历
        </el-button>
        <el-tooltip
          v-else
          content="请完成所有步骤后再生成简历"
          placement="bottom"
        >
          <el-button type="primary" disabled>
            <el-icon><Download /></el-icon>
            生成简历
          </el-button>
        </el-tooltip>
      </div>
    </div>

    <div class="builder-content" v-loading="loading">
      <div class="builder-sidebar">
        <div class="progress-section">
          <div class="progress-title">完成进度</div>
          <el-progress
            :percentage="completionRate"
            :stroke-width="8"
            :show-text="false"
          />
          <div class="progress-text">{{ completionRate }}%</div>
        </div>

        <div class="steps-section">
          <div class="step-item"
            v-for="(step, index) in steps"
            :key="step.key"
            :class="{
              active: currentStep === index,
              completed: step.completed
            }"
            @click="handleStepClick(index)"
          >
            <div class="step-icon">
              <el-icon v-if="step.completed"><Check /></el-icon>
              <span v-else>{{ index + 1 }}</span>
            </div>
            <div class="step-info">
              <div class="step-title">{{ step.title }}</div>
              <div class="step-desc">{{ step.description }}</div>
            </div>
          </div>
        </div>
      </div>

      <div class="builder-main">
        <div class="step-content">
          <!-- 基本信息 -->
          <BasicInfoStep
            v-if="currentStep === 0"
            :resume-id="resumeId"
            @completed="handleStepCompleted(0, $event)"
            @data-saved="handleDataSaved"
          />

          <!-- 教育背景 -->
          <EducationStep
            v-if="currentStep === 1"
            :resume-id="resumeId"
            @completed="handleStepCompleted(1, $event)"
            @data-saved="handleDataSaved"
          />

          <!-- 专业技能 -->
          <SkillStep
            v-if="currentStep === 2"
            :resume-id="resumeId"
            @completed="handleStepCompleted(2, $event)"
            @data-saved="handleDataSaved"
          />

          <!-- 项目经验 -->
          <ProjectStep
            v-if="currentStep === 3"
            :resume-id="resumeId"
            @completed="handleStepCompleted(3, $event)"
            @data-saved="handleDataSaved"
          />

          <!-- 工作经验 -->
          <WorkExperienceStep
            v-if="currentStep === 4"
            :resume-id="resumeId"
            @completed="handleStepCompleted(4, $event)"
            @data-saved="handleDataSaved"
          />

          <!-- 获奖经历 -->
          <AwardStep
            v-if="currentStep === 5"
            :resume-id="resumeId"
            @completed="handleStepCompleted(5, $event)"
            @data-saved="handleDataSaved"
          />

          <!-- 自我介绍 -->
          <SelfIntroductionStep
            v-if="currentStep === 6"
            :resume-id="resumeId"
            @completed="handleStepCompleted(6, $event)"
            @data-saved="handleDataSaved"
          />
        </div>

        <div class="step-navigation">
          <el-button
            @click="handlePrevStep"
            :disabled="currentStep === 0"
          >
            上一步
          </el-button>
          <el-button
            type="primary"
            @click="handleNextStep"
            :disabled="currentStep === steps.length - 1"
          >
            下一步
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted, h } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  resumeApi,
  basicInfoApi,
  educationApi,
  skillApi,
  projectApi,
  workExperienceApi,
  awardApi,
  selfIntroductionApi,
  type Resume
} from '@/api/resume'

// 导入步骤组件
import BasicInfoStep from './components/steps/BasicInfoStep.vue'
import EducationStep from './components/steps/EducationStep.vue'
import SkillStep from './components/steps/SkillStep.vue'
import ProjectStep from './components/steps/ProjectStep.vue'
import WorkExperienceStep from './components/steps/WorkExperienceStep.vue'
import AwardStep from './components/steps/AwardStep.vue'
import SelfIntroductionStep from './components/steps/SelfIntroductionStep.vue'

const route = useRoute()
const router = useRouter()

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const generating = ref(false)
const refreshing = ref(false)
const currentStep = ref(0)
const resumeData = ref<Resume | null>(null)

// 简历ID
const resumeId = computed(() => {
  return parseInt(route.params.id as string)
})

// 步骤配置
const steps = reactive([
  {
    key: 'basic',
    title: '基本信息',
    description: '姓名、联系方式等',
    completed: false
  },
  {
    key: 'education',
    title: '教育背景',
    description: '学历、专业等',
    completed: false
  },
  {
    key: 'skills',
    title: '专业技能',
    description: '技能水平等',
    completed: false
  },
  {
    key: 'projects',
    title: '项目经验',
    description: '项目描述、成果等',
    completed: false
  },
  {
    key: 'work',
    title: '工作经验',
    description: '工作经历、职责等（可选）',
    completed: false
  },
  {
    key: 'awards',
    title: '获奖经历',
    description: '奖项、证书等（可选）',
    completed: false
  },
  {
    key: 'introduction',
    title: '自我介绍',
    description: '个人简介等',
    completed: false
  }
])

// 计算完成率
const completionRate = computed(() => {
  const completedCount = steps.filter(step => step.completed).length
  return Math.round((completedCount / steps.length) * 100)
})

// 检查所有步骤是否完成
const allStepsCompleted = computed(() => {
  return steps.every(step => step.completed)
})

// 检查resumeId是否有效
const isValidResumeId = (): boolean => {
  return !!(resumeId.value && !isNaN(resumeId.value))
}

// 获取简历详情
const fetchResumeDetail = async () => {
  loading.value = true
  try {
    const response = await resumeApi.getResumeDetail(resumeId.value)
    const data = response.data || response
    resumeData.value = data

    // 根据简历数据更新步骤完成状态
    updateStepsCompletion(data)
  } catch (error) {
    ElMessage.error('获取简历详情失败')
  } finally {
    loading.value = false
  }
}

// 更新步骤完成状态
const updateStepsCompletion = async (resume: Resume) => {
  try {
    // 检查resumeId是否有效
    if (!resumeId.value || isNaN(resumeId.value)) {
      return
    }

    // 检测每个步骤的数据完成状态
    const stepCompletionStatus = await Promise.all([
      checkBasicInfoCompletion(),      // 基本信息
      checkEducationCompletion(),      // 教育背景
      checkSkillsCompletion(),         // 专业技能
      checkProjectsCompletion(),       // 项目经验
      checkWorkExperienceCompletion(), // 工作经验
      checkAwardsCompletion(),         // 获奖经历
      checkSelfIntroductionCompletion() // 自我介绍
    ])

    // 更新步骤完成状态
    steps.forEach((step, index) => {
      step.completed = stepCompletionStatus[index] || false
    })

    // 计算并更新完成率
    await updateCompletionRate()
  } catch (error) {
    console.error('更新步骤完成状态失败:', error)
  }
}

// 检测基本信息完成状态
const checkBasicInfoCompletion = async (): Promise<boolean> => {
  try {
    if (!resumeId.value || isNaN(resumeId.value)) {
      return false
    }

    const response = await basicInfoApi.getBasicInfo(resumeId.value)
    const data = response.data || response

    // 处理分页格式的响应
    let basicInfo = null
    if (Array.isArray(data)) {
      basicInfo = data.length > 0 ? data[0] : null
    } else if (data && data.results && Array.isArray(data.results)) {
      basicInfo = data.results.length > 0 ? data.results[0] : null
    } else if (data && data.name) {
      basicInfo = data
    }

    // 检查必填字段
    if (basicInfo && basicInfo.name && basicInfo.phone && basicInfo.email) {
      return true
    }
    return false
  } catch (error) {
    console.error('检测基本信息完成状态失败:', error)
    return false
  }
}

// 检测教育背景完成状态
const checkEducationCompletion = async (): Promise<boolean> => {
  try {
    if (!isValidResumeId()) return false

    const response = await educationApi.getEducationList(resumeId.value)
    const data = response.data || response
    const educationList = Array.isArray(data) ? data : (data.results || [])

    // 至少有一条教育背景记录
    return educationList.length > 0 && educationList.some((edu: any) =>
      edu.school_name && edu.major && edu.degree
    )
  } catch (error) {
    console.error('检测教育背景完成状态失败:', error)
    return false
  }
}

// 检测专业技能完成状态
const checkSkillsCompletion = async (): Promise<boolean> => {
  try {
    if (!isValidResumeId()) return false

    const response = await skillApi.getSkillList(resumeId.value)
    const data = response.data || response
    const skillsList = Array.isArray(data) ? data : (data.results || [])

    // 至少有一条技能记录
    return skillsList.length > 0 && skillsList.some((skill: any) => skill.name)
  } catch (error) {
    return false
  }
}

// 检测项目经验完成状态
const checkProjectsCompletion = async (): Promise<boolean> => {
  try {
    if (!isValidResumeId()) return false

    const response = await projectApi.getProjectList(resumeId.value)
    const data = response.data || response
    const projectsList = Array.isArray(data) ? data : (data.results || [])

    // 至少有一条项目记录
    return projectsList.length > 0 && projectsList.some((project: any) =>
      project.name && project.overview
    )
  } catch (error) {
    return false
  }
}

// 检测工作经验完成状态
const checkWorkExperienceCompletion = async (): Promise<boolean> => {
  try {
    if (!isValidResumeId()) return true // 无效ID时返回true（可选步骤）

    const response = await workExperienceApi.getWorkExperienceList(resumeId.value)
    const data = response.data || response
    const workList = Array.isArray(data) ? data : (data.results || [])

    // 工作经验是可选的，但如果有记录则必须完整
    console.log(workList, "工作经验列表")
    if (workList.length === 0) {
      return false // 没有工作经验也算完成（对学生来说是可选的）| 修改为必选
    }

    // 如果有工作经验，检查是否填写完整
    return workList.some((work: any) =>
      work.company_name && work.position_name && work.job_responsibilities
    )
  } catch (error) {
    return false
  }
}

// 检测获奖经历完成状态
const checkAwardsCompletion = async (): Promise<boolean> => {
  try {
    if (!isValidResumeId()) return true // 无效ID时返回true（可选步骤）

    const response = await awardApi.getAwardList(resumeId.value)
    const data = response.data || response
    const awardsList = Array.isArray(data) ? data : (data.results || [])

    // 获奖经历是可选的，但如果有记录则必须完整
    if (awardsList.length === 0) {
      return false // 没有获奖经历也算完成（对学生来说是可选的）| 修改为必选
    }

    // 如果有获奖经历，检查是否填写完整
    return awardsList.some((award: any) =>
      award.award_name && award.award_name.trim().length > 0
    )
  } catch (error) {
    return false
  }
}

// 检测自我介绍完成状态
const checkSelfIntroductionCompletion = async (): Promise<boolean> => {
  try {
    if (!isValidResumeId()) return false

    const response = await selfIntroductionApi.getSelfIntroduction(resumeId.value)
    const data = response.data || response

    // 检查自我介绍内容
    if (Array.isArray(data)) {
      return data.length > 0 && data[0].content && data[0].content.trim().length > 0
    } else if (data && data.content) {
      return data.content.trim().length > 0
    }
    return false
  } catch (error) {
    return false
  }
}

// 更新完成率到服务器
const updateCompletionRate = async () => {
  try {
    // 调用后端API重新计算完成度
    const response = await resumeApi.updateCompletion(resumeId.value)
    const newRate = response.data.completion_rate

    // 准备更新数据
    const updateData: any = {
      current_step: currentStep.value + 1
    }

    // 如果简历状态是draft，更新为in_progress
    if (resumeData.value?.status === 'draft') {
      updateData.status = 'in_progress'
    }

    // 更新当前步骤和状态到服务器
    await resumeApi.updateResume(resumeId.value, updateData)

    // 更新本地数据
    if (resumeData.value) {
      resumeData.value.completion_rate = newRate
      if (updateData.status) {
        resumeData.value.status = updateData.status
      }
    }

    console.log(`完成度已更新为: ${newRate}%`)
  } catch (error) {
    console.error('更新完成率失败:', error)
    // 如果API调用失败，使用前端计算的完成度作为备选
    const completedCount = steps.filter(step => step.completed).length
    const rate = Math.round((completedCount / steps.length) * 100)

    try {
      const updateData: any = {
        completion_rate: rate,
        current_step: currentStep.value + 1
      }

      // 如果简历状态是draft，更新为in_progress
      if (resumeData.value?.status === 'draft') {
        updateData.status = 'in_progress'
      }

      await resumeApi.updateResume(resumeId.value, updateData)

      if (resumeData.value) {
        resumeData.value.completion_rate = rate
        if (updateData.status) {
          resumeData.value.status = updateData.status
        }
      }
    } catch (fallbackError) {
      console.error('备选更新方案也失败:', fallbackError)
    }
  }
}

// 处理步骤点击
const handleStepClick = async (stepIndex: number) => {
  currentStep.value = stepIndex

  // 切换步骤时检测当前步骤的完成状态
  if (resumeData.value) {
    await updateStepsCompletion(resumeData.value)
  }
}

// 手动刷新步骤状态
const refreshStepsStatus = async () => {
  if (!resumeData.value) return

  refreshing.value = true
  try {
    await updateStepsCompletion(resumeData.value)
    ElMessage.success('步骤状态已刷新')
  } catch (error) {
    console.error('刷新步骤状态失败:', error)
    ElMessage.error('刷新失败')
  } finally {
    refreshing.value = false
  }
}

// 处理数据保存事件
const handleDataSaved = async () => {
  // 重新检测所有步骤的完成状态
  await updateStepsCompletion(resumeData.value!)
}

// 处理步骤完成
const handleStepCompleted = async (stepIndex: number, completed: boolean) => {
  steps[stepIndex].completed = completed

  // 更新完成率
  await updateCompletionRate()

  // 自动保存（静默保存，不显示提示）
  autoSave()
}

// 处理上一步
const handlePrevStep = () => {
  if (currentStep.value > 0) {
    currentStep.value--
  }
}

// 处理下一步
const handleNextStep = () => {
  if (currentStep.value < steps.length - 1) {
    currentStep.value++
  }
}

// 自动保存（静默）
const autoSave = async () => {
  try {
    // 更新简历的完成率
    await resumeApi.updateResume(resumeId.value, {
      completion_rate: completionRate.value,
      current_step: currentStep.value
    })
  } catch (error) {
    console.error('自动保存失败:', error)
  }
}

// 处理手动保存
const handleSave = async () => {
  saving.value = true
  try {
    // 更新简历的完成率
    await resumeApi.updateResume(resumeId.value, {
      completion_rate: completionRate.value,
      current_step: currentStep.value
    })

    ElMessage.success('保存成功')
  } catch (error) {
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}

// 格式选择对话框
const showFormatSelectionDialog = async () => {
  try {
    const { value } = await ElMessageBox.confirm(
      '请选择简历生成格式：\n\n• Word文档 (.docx) - 推荐格式\n• PDF文档 (.pdf) - 通用格式',
      '选择简历格式',
      {
        confirmButtonText: 'Word格式',
        cancelButtonText: 'PDF格式',
        distinguishCancelAndClose: true,
        type: 'info'
      }
    )
    return 'docx' // 确认按钮选择Word格式
  } catch (action) {
    if (action === 'cancel') {
      return 'pdf' // 取消按钮选择PDF格式
    }
    throw action // 关闭对话框
  }
}

// 处理生成简历
const handleGenerate = async () => {
  try {
    // 检查所有步骤是否完成
    if (!allStepsCompleted.value) {
      ElMessage.warning('请完成所有步骤后再生成简历')
      return
    }

    // 使用自定义对话框进行格式选择
    const format = await showFormatSelectionDialog()

    generating.value = true

    // 调用生成API，传入格式参数
    const response = await resumeApi.generateResume(resumeId.value, format)

    // 处理生成结果
    const result = response.data || response

    if (result.file_url) {
      // 显示生成成功消息并询问是否立即下载
      await ElMessageBox.confirm(
        `简历生成成功！\n\n文件名：${result.file_name}\n格式：${result.file_type.toUpperCase()}\n\n是否立即下载？`,
        '简历生成成功',
        {
          confirmButtonText: '立即下载',
          cancelButtonText: '稍后下载',
          type: 'success',
          distinguishCancelAndClose: true
        }
      ).then(() => {
        // 用户选择立即下载
        downloadGeneratedFile(result.download_url, result.file_name)
      }).catch((action) => {
        if (action === 'cancel') {
          // 用户选择稍后下载
          ElMessage.info('简历已生成，您可以稍后在简历列表中下载')
        }
      })
    } else {
      ElMessage.success('简历生成成功')
    }

    // 刷新简历数据
    await fetchResumeDetail()

  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('生成简历错误:', error)
      ElMessage.error('生成失败')
    }
  } finally {
    generating.value = false
  }
}

// 下载生成的文件
const downloadGeneratedFile = async (downloadUrl: string, fileName: string) => {
  try {
    const response = await fetch(downloadUrl, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('access_token')}`
      }
    })

    if (!response.ok) {
      throw new Error('下载失败')
    }

    const blob = await response.blob()
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = fileName
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)

    ElMessage.success('文件下载成功')
  } catch (error) {
    console.error('下载文件错误:', error)
    ElMessage.error('下载失败')
  }
}

// 返回
const goBack = () => {
  // 添加时间戳参数强制刷新列表页面
  router.push({
    path: '/resume/my',
    query: { refresh: Date.now().toString() }
  })
}

// 生命周期
onMounted(async () => {
  await fetchResumeDetail()

  // 初始检测步骤完成状态
  if (resumeData.value) {
    await updateStepsCompletion(resumeData.value)
  }

  // 延迟再次检测，确保新创建的简历能正确检测状态
  setTimeout(async () => {
    if (resumeData.value) {
      await updateStepsCompletion(resumeData.value)
    }
  }, 2000) // 2秒后再次检测

  // 设置定时检测步骤完成状态（降低频率）
  const checkInterval = setInterval(async () => {
    if (resumeData.value) {
      await updateStepsCompletion(resumeData.value)
    }
  }, 30000) // 每30秒检测一次

  // 页面卸载时清除定时器
  const cleanup = () => {
    clearInterval(checkInterval)
  }

  // 监听页面卸载
  window.addEventListener('beforeunload', cleanup)
})
</script>

<style lang="scss" scoped>
.resume-builder {
  height: 100vh;
  display: flex;
  flex-direction: column;

  .builder-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 24px;
    border-bottom: 1px solid var(--border-color-light);
    background: var(--bg-color);

    .header-left {
      display: flex;
      align-items: center;
      gap: 12px;

      .resume-title {
        font-size: 18px;
        font-weight: 600;
        color: var(--text-color-primary);
      }
    }

    .header-right {
      display: flex;
      gap: 12px;
    }
  }

  .builder-content {
    flex: 1;
    display: flex;
    overflow: hidden;

    .builder-sidebar {
      width: 280px;
      border-right: 1px solid var(--border-color-light);
      background: var(--fill-color-extra-light);
      padding: 24px;

      .progress-section {
        margin-bottom: 32px;

        .progress-title {
          font-size: 14px;
          font-weight: 600;
          color: var(--text-color-primary);
          margin-bottom: 12px;
        }

        .progress-text {
          text-align: center;
          margin-top: 8px;
          font-size: 14px;
          color: var(--text-color-secondary);
        }
      }

      .steps-section {
        .step-item {
          display: flex;
          align-items: center;
          padding: 16px;
          border-radius: 8px;
          cursor: pointer;
          transition: all 0.3s ease;
          margin-bottom: 8px;

          &:hover {
            background: var(--fill-color-light);
          }

          &.active {
            background: var(--color-primary-light-9);
            border: 1px solid var(--color-primary-light-7);
          }

          &.completed {
            .step-icon {
              background: var(--color-success);
              color: white;
            }
          }

          .step-icon {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            background: var(--fill-color);
            border: 2px solid var(--border-color-light);
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 12px;
            font-size: 14px;
            font-weight: 600;
            color: var(--text-color-secondary);
          }

          .step-info {
            flex: 1;

            .step-title {
              font-size: 14px;
              font-weight: 600;
              color: var(--text-color-primary);
              margin-bottom: 4px;
            }

            .step-desc {
              font-size: 12px;
              color: var(--text-color-secondary);
            }
          }
        }
      }
    }

    .builder-main {
      flex: 1;
      display: flex;
      flex-direction: column;
      overflow: hidden;

      .step-content {
        flex: 1;
        overflow-y: auto;
        padding: 24px;
      }

      .step-navigation {
        padding: 16px 24px;
        border-top: 1px solid var(--border-color-light);
        display: flex;
        justify-content: space-between;
        background: var(--bg-color);
      }
    }
  }
}

@media (max-width: 768px) {
  .resume-builder {
    .builder-content {
      flex-direction: column;

      .builder-sidebar {
        width: 100%;
        border-right: none;
        border-bottom: 1px solid var(--border-color-light);
        padding: 16px;

        .steps-section {
          display: flex;
          overflow-x: auto;
          gap: 8px;

          .step-item {
            min-width: 120px;
            margin-bottom: 0;
          }
        }
      }
    }
  }
}
</style>
